import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import pool from '../config/database.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export const PhotoController = {
  async getPhotos(req, res) {
    try {
      const [rows] = await pool.query('SELECT * FROM photos ORDER BY created_at DESC');
      res.json(rows);
    } catch (error) {
      console.error('Error fetching photos:', error);
      res.status(500).json({ error: 'Failed to fetch photos' });
    }
  },

  async uploadPhoto(req, res) {
    try {
      if (!req.file) {
        return res.status(400).json({ error: 'No file uploaded' });
      }

      const photoUrl = `/uploads/${req.file.filename}`;
      const [result] = await pool.query(
        'INSERT INTO photos (title, description, url) VALUES (?, ?, ?)',
        [req.body.title || 'Untitled', req.body.description || '', photoUrl]
      );

      const [newPhoto] = await pool.query('SELECT * FROM photos WHERE id = ?', [result.insertId]);
      res.status(201).json(newPhoto[0]);
    } catch (error) {
      console.error('Error uploading photo:', error);
      res.status(500).json({ error: 'Failed to upload photo' });
    }
  },

  async deletePhoto(req, res) {
    try {
      const [photo] = await pool.query('SELECT url FROM photos WHERE id = ?', [req.params.id]);
      if (photo.length === 0) {
        return res.status(404).json({ error: 'Photo not found' });
      }

      const filePath = path.join(__dirname, '../../public', photo[0].url);
      try {
        await fs.unlink(filePath);
      } catch (err) {
        console.error('Error deleting file:', err);
      }

      await pool.query('DELETE FROM photos WHERE id = ?', [req.params.id]);
      res.status(204).send();
    } catch (error) {
      console.error('Error deleting photo:', error);
      res.status(500).json({ error: 'Failed to delete photo' });
    }
  }
};